package it.hive.mediaplayer.listeners;

import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

public class MediaPlayerPlayTimeListener implements ChangeListener<Duration> {
	private MediaPlayer player;
	private String nomeTraccia;
	private SimpleDoubleProperty playProgress;
	private SimpleStringProperty playTime;

	public MediaPlayerPlayTimeListener(MediaPlayer mediaPlayer, String nomeTraccia) {
		player = mediaPlayer;
		this.nomeTraccia = "In riproduzione " + nomeTraccia;
		player.currentTimeProperty().addListener(this);
		playProgress = new SimpleDoubleProperty(-1);
		playTime = new SimpleStringProperty();
	}

	public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
		if (player != null) {
			playProgress.set(1.0 * player.getCurrentTime().toMillis() / player.getTotalDuration().toMillis());
			playTime.set(nomeTraccia + " [" + formatTime(player.getCurrentTime(), player.getTotalDuration()) + "]");
		}
		if (newValue == null) {
			playTime.set("");
		}
	}

	public final SimpleDoubleProperty getPlayProgress() {
		return playProgress;
	}

	public final SimpleStringProperty getPlayTimeProgress() {
		return playTime;
	}

	private static String formatTime(Duration elapsed, Duration duration) {
		int intElapsed = (int) Math.floor(elapsed.toSeconds());
		int elapsedHours = intElapsed / (60 * 60);
		if (elapsedHours > 0) {
			intElapsed -= elapsedHours * 60 * 60;
		}
		int elapsedMinutes = intElapsed / 60;
		int elapsedSeconds = intElapsed - elapsedHours * 60 * 60 - elapsedMinutes * 60;
		if (duration.greaterThan(Duration.ZERO)) {
			int intDuration = (int) Math.floor(duration.toSeconds());
			int durationHours = intDuration / (60 * 60);
			if (durationHours > 0) {
				intDuration -= durationHours * 60 * 60;
			}
			if (durationHours > 0) {
				return String.format("%d:%02d:%02d", elapsedHours, elapsedMinutes, elapsedSeconds);
			} else {
				return String.format("%02d:%02d", elapsedMinutes, elapsedSeconds);
			}
		} else {
			if (elapsedHours > 0) {
				return String.format("%d:%02d:%02d", elapsedHours, elapsedMinutes, elapsedSeconds);
			} else {
				return String.format("%02d:%02d", elapsedMinutes, elapsedSeconds);
			}
		}
	}
}
